package com.atguigu.education.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.education.bean.PaperScoreBean;
import com.atguigu.education.util.ClickHouseUtil;
import com.atguigu.education.util.DateFormatUtil;
import com.atguigu.education.util.KafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsPaperScoreWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // TODO 2 设置后端状态
        /*
           env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
           env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
           env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
           env.setStateBackend(new HashMapStateBackend());
           env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
           System.setProperty("HADOOP_USER_NAME", "atguigu");
        */
        // TODO 3 从Kafka对应主题中读取数据
        String topicName = "dwd_test_exam";
        String groupID = "dws_paper_score_window";
        DataStreamSource<String> paperScoreStream = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupID));

        // TODO 4 flatmap转换结构为javabean，并使用if语句判断各分数段人数
        SingleOutputStreamOperator<PaperScoreBean> flatmapStream =
                paperScoreStream.flatMap(new FlatMapFunction<String, PaperScoreBean>() {
                    @Override
                    public void flatMap(String value, Collector<PaperScoreBean> out) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(value);
                        String paperId = jsonObject.getString("paper_id");
                        Long score = jsonObject.getLong("score");
                        Long ts = DateFormatUtil.toTs(jsonObject.getString("submit_time"), true);
                        if (score >= 0 && score <= 20) {
                            out.collect(new PaperScoreBean("", "", paperId, 1L, 0L, 0L, 0L, 0L, ts));
                        }
                        if (score >= 21 && score <= 40) {
                            out.collect(new PaperScoreBean("", "", paperId, 0L, 1L, 0L, 0L, 0L, ts));
                        }
                        if (score >= 41 && score <= 60) {
                            out.collect(new PaperScoreBean("", "", paperId, 0L, 0L, 1L, 0L, 0L, ts));
                        }
                        if (score >= 61 && score <= 80) {
                            out.collect(new PaperScoreBean("", "", paperId, 0L, 0L, 0L, 1L, 0L, ts));
                        }
                        if (score >= 81 && score <= 100) {
                            out.collect(new PaperScoreBean("", "", paperId, 0L, 0L, 0L, 0L, 1L, ts));
                        }
                    }
                });

        // TODO 5 设置水位线
        SingleOutputStreamOperator < PaperScoreBean > beanWithWatermarkStream = flatmapStream
                .assignTimestampsAndWatermarks(WatermarkStrategy.<PaperScoreBean>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                        .withTimestampAssigner(new SerializableTimestampAssigner<PaperScoreBean>() {
                            @Override
                            public long extractTimestamp(PaperScoreBean element, long recordTimestamp) {
                                return element.getTs();
                            }
                        }));

        // TODO 6 按试卷id分组
        KeyedStream<PaperScoreBean, String> keyedStream = beanWithWatermarkStream.keyBy(new KeySelector<PaperScoreBean, String>() {
            @Override
            public String getKey(PaperScoreBean value) throws Exception {
                return value.getPaperId();
            }
        });

        // TODO 7 开窗聚合
        SingleOutputStreamOperator<PaperScoreBean> reducedStream =
                keyedStream.window(TumblingEventTimeWindows.of(Time.seconds(10L)))
                        .reduce(new ReduceFunction<PaperScoreBean>() {
                            @Override
                            public PaperScoreBean reduce(PaperScoreBean value1, PaperScoreBean value2) throws Exception {
                                value1.setFirstCount(value1.getFirstCount() + value2.getFirstCount());
                                value1.setSecondCount(value1.getSecondCount() + value2.getSecondCount());
                                value1.setThirdCount(value1.getThirdCount() + value2.getThirdCount());
                                value1.setFourthCount(value1.getFourthCount() + value2.getFourthCount());
                                value1.setFifthCount(value1.getFifthCount() + value2.getFifthCount());
                                return value1;
                            }
                        }, new WindowFunction<PaperScoreBean, PaperScoreBean, String, TimeWindow>() {
                            @Override
                            public void apply(String s, TimeWindow window, Iterable<PaperScoreBean> input, Collector<PaperScoreBean> out) throws Exception {
                                PaperScoreBean paperScoreBean = input.iterator().next();
                                paperScoreBean.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                                paperScoreBean.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                                paperScoreBean.setTs(System.currentTimeMillis());
                                out.collect(paperScoreBean);
                            }
                        });
        // TODO 8 写入clickHouse
        reducedStream.addSink(ClickHouseUtil.getClickHouseSinkFunc("insert into dws_paper_score_window values" +
                "(?,?,?,?,?,?,?,?,?)"));
        // TODO 9 执行
        env.execute(groupID);
    }
}
